<?php namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\UserLoginRequest;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Foundation\Auth\User;
use Illuminate\Support\Facades\DB;

class AuthController extends Controller
{

    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers;

    /**
     * Create a new authentication controller instance.
     *
     * @param  \Illuminate\Contracts\Auth\Guard $auth
     * @param  \Illuminate\Contracts\Auth\Registrar $registrar
     * @return void
     */
    public function __construct()
    {
        \Auth::logout();
    }

    /**
     * Show the application login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function getLogin()
    {
        return view('admin.auth.login');
    }

    /**
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function postLogin(UserLoginRequest $request)
    {
        $this->validate($request, [
            'name' => 'required', 'password' => 'required',
        ], ['name.required' => '账号为必填项']);

        $credentials = $request->only('name', 'password');
        $status = DB::table('admins')->where('name', $request->name)->first();
        if (isset($status->status) && 0 == $status->status) {
            return redirect('/admin/auth/login')
                ->withInput($request->only('name', 'remember'))
                ->withErrors([
                    'name' => '账号被禁用',
                ]);
        }
        if (\Auth::attempt($credentials, $request->has('remember'))) {
            return redirect()->intended($this->redirectPath());
        }

        return redirect('/admin/auth/login')
            ->withInput($request->only('name', 'remember'))
            ->withErrors([
//                'name' => $this->getFailedLoginMessage(),
                'name' => '账号或密码错误',
            ]);
    }

    public function getLogout()
    {
        if (Auth::check()) {
            abort(404);
        }
        Auth::logout();
    }
}
